const Promise = require('bluebird');
const emoji = require('node-emoji');

/**
 * @api {get} /api/admin/v1/settings/load 设置详情
 * @apiGroup AdminSettings
 * @apiDescription 设置管理-设置详情
 * @apiPermission 管理员(查看设置权限)
 * @apiVersion 1.0.0
 *
 * @apiUse apiLoadResult
 */
exports.load = function ({}, {models: {Settings}}) {
    return Settings.findToMapV2();
}

/**
 * @api {post} /api/admin/v1/settings/save 设置保存
 * @apiGroup AdminSettings
 * @apiDescription 设置管理-设置保存
 * @apiPermission 管理员(编辑设置权限)
 * @apiVersion 1.0.0
 *
 * @apiUse apiSuccessResult
 */
exports.save = function ({body}, {models: {Settings}, redis}) {
    let updates = [];
    for (let name in body) {
        updates.push(Settings.update({value: body[name]}, {where: {name: name}}));
    }
    return Promise.all(updates).then(function () {
        /**
         * 推送设置更新消息
         */
        redis.pub.publish('settings_update', 'settings_update');
        return {success: true};
    });
};

exports.wechatUpdate = function ({body}, {models: {Settings}, redis, wechatInstance}) {
    let updates = [];
    for (let name in body) {
        updates.push(Settings.update({value: body[name]}, {where: {name: name}}));
    }
    return Promise.all(updates).then(function () {
        /**
         * 推送设置更新消息
         */
        redis.pub.publish('settings_update', 'settings_update');

        if (body.wechat_menu) {
            return new Promise(function (resolve) {
                wechatInstance.shopWebApi.createMenu(JSON.parse(body.wechat_menu), function (err, result) {
                    if (err) {
                        console.error('\n', err.stack || err.message);
                        return resolve({success: false, message: '调用微信出错'});
                    }
                    console.log('create_wechat_menu', result);
                    return resolve({success: true});
                });
            });
        } else if (body.wechat_menu === '') {
            return new Promise(function (resolve) {
                wechatInstance.shopWebApi.removeMenu(function (err, result) {
                    if (err) {
                        console.error('\n', err.stack || err.message);
                        return resolve({success: false, message: '调用微信出错'});
                    }
                    console.log('remove_wechat_menu', result);
                    return resolve({success: true});
                });
            });
        }
        return {success: true};
    });
};

/**
 * @api {get} /api/admin/v1/settings/reindex_goodses_search 重建商品搜索索引
 * @apiGroup AdminSettings
 * @apiDescription 设置管理-重建商品搜索索引
 * @apiPermission 管理员(编辑设置权限)
 * @apiVersion 1.0.0
 *
 * @apiUse apiSuccessResult
 */
let reindexing = false;
exports.reindexGoodsesSearch = function ({}, {modelsData: {Goodses}, models: {}, search: {searchEnable, goodsesSearch}}) {
    if (reindexing) {
        return {success: false, message: '正在重建中，不要重复执行'};
    }
    reindexing = true;

    let limit = 20, where = {status: 'Active'};
    let handler = function () {
        console.log('reindexGoodsesSearch', where);

        return Goodses.findAll({
            where: where,
            order: [['id', 'desc']],
            limit: limit,
            raw: true
        }).then(function (goodses) {
            return Promise.mapSeries(goodses, function (goods) {
                return goodsesSearch.index(goods)
            }, {concurrency: 1}).then(function () {
                if (goodses.length == limit) {
                    where = {id: {$lt: goodses[limit - 1].id}};
                    return handler();
                }

                reindexing = false;
                return {success: true};
            });
        }).catch(function (err) {
            if (err) {
                console.error('\n', err.stack || err.message);
            }

            reindexing = false;
            return {success: false};
        });
    }
    if (!searchEnable) {
        return {success: false, message: '搜索功能不可用, 可能没有部署索引服务器'};
    }

    return goodsesSearch.drop().then(function (result) {
        if (!result.success) {
            reindexing = false;
            return {success: false, message: '重建索引失败'}
        }
        handler();
        return {success: true};
    });
}


/**
 * @api {get} /api/admin/v1/settings/recapture_user_data 重新获取用户微信数据
 * @apiGroup AdminSettings
 * @apiDescription 设置管理-重新获取用户微信数据
 * @apiPermission 管理员(编辑设置权限)
 * @apiVersion 1.0.0
 *
 * @apiUse apiSuccessResult
 */
let recaptureing = false;
exports.recaptureUserData = function ({query}, {models: {Users}, wechatInstance}) {
    if (recaptureing) {
        return {success: false, message: '正在获取中，不要重复执行'};
    }
    recaptureing = true;

    let limit = 20, where = {};
    if (query.subscribe !== undefined) {
        where.subscribe = query.subscribe
    }
    let handler = function () {
        console.log('recaptureUserData', where);

        return Users.findAll({
            where: where,
            order: [['id', 'desc']],
            limit: limit,
            raw: true
        }).then(function (users) {
            return Promise.mapSeries(users, function (user) {
                console.log(user.id, user.openid);

                if (!user.openid) {
                    return;
                }
                return new Promise(function (resolve) {
                    wechatInstance.shopWebApi.getUser(user.openid, function (err, result) {
                        if (err) {
                            console.error('\n', err.stack || err.message);

                            Users.update({subscribe: 0}, {where: {id: user.id}});
                            return resolve({success: false});
                        }
                        console.log(result);

                        if (result.openid) {
                            Users.update({
                                subscribe: result.subscribe,
                                sex: result.sex,
                                ext_data: emoji.strip(JSON.stringify(result))
                            }, {where: {id: user.id}});
                        } else {
                            Users.update({subscribe: 0}, {where: {id: user.id}});
                        }
                        return resolve({success: true});
                    });
                });

            }, {concurrency: 1}).then(function () {
                if (users.length == limit) {
                    where.id = {$lt: users[limit - 1].id};
                    return handler();
                }

                recaptureing = false;
                return {success: true};
            });
        }).catch(function (err) {
            if (err) {
                console.error('\n', err.stack || err.message);
            }

            recaptureing = false;
            return {success: false};
        });
    }
    handler();
    return {success: true};
}


/**
 * @api {get} /api/admin/v1/settings/update_wechat_tags 更新用户标签
 * @apiGroup AdminSettings
 * @apiDescription 设置管理-更新用户标签
 * @apiPermission 管理员(编辑设置权限)
 * @apiVersion 1.0.0
 *
 * @apiUse apiSuccessResult
 */
let updateing = false;
exports.updateWechatTags = function ({query}, {models: {Users}, cache: {dicts}, wechatInstance}) {
    if (updateing) {
        return {success: false, message: '正在更新中，不要重复执行'};
    }
    updateing = true;

    return Users.findAll({where: {level: 'Partner'}, raw: true}).then(function (users) {
        return Promise.mapSeries(users, function (user) {
            let limit = 50, where = {partner_id: user.id};
            let handler = function () {
                console.log('updateWechatTags', where);

                return Users.findAll({
                    where: where,
                    limit: limit,
                    attributes: ['id', 'openid'],
                    order: [['id', 'desc']],
                    raw: true
                }).then(function (userList) {
                    let dictValue = dicts.text('user_tag', user.id);
                    if (dictValue) {
                        let tagId = dictValue.split('_')[1];
                        if (tagId) {
                            return new Promise(function (resolve) {
                                let openids = [];
                                for (let i in userList) {
                                    openids.push(userList[i].openid);
                                }
                                wechatInstance.shopWebApi.membersBatchtagging(tagId, openids, function (err, result) {
                                    if (err) {
                                        console.error('\n', err.stack || err.message);
                                    }
                                    console.log(tagId, openids, result);
                                    resolve();
                                });
                            }).then(function () {
                                if (userList.length == limit) {
                                    where.id = {$lt: userList[limit - 1].id};
                                    return handler();
                                }
                                return {success: true};
                            });
                        }
                    }
                });
            }
            return handler();
        }).then(function () {
            let dictValue = dicts.text('user_tag', 'agency');
            if (dictValue) {
                let tagId = dictValue.split('_')[1];
                if (tagId) {
                    let limit = 50, where = {level: 'Agency'};
                    let handler = function () {
                        return Users.findAll({
                            where: where,
                            limit: limit,
                            attributes: ['id', 'openid'],
                            order: [['id', 'desc']],
                            raw: true
                        }).then(function (userList) {
                            return new Promise(function (resolve) {
                                let openids = [];
                                for (let i in userList) {
                                    openids.push(userList[i].openid);
                                }
                                wechatInstance.shopWebApi.membersBatchtagging(tagId, openids, function (err, result) {
                                    if (err) {
                                        console.error('\n', err.stack || err.message);
                                    }
                                    console.log(tagId, openids, result);
                                    resolve();
                                });
                            }).then(function () {
                                if (userList.length == limit) {
                                    where.id = {$lt: userList[limit - 1].id};
                                    return handler();
                                }
                                return {success: true};
                            });
                        });
                    }
                    return handler();
                }
            }
        });
    }).then(function () {
        updateing = false;
        return {success: true};
    }).catch(function (err) {
        if (err) {
            console.error('\n', err.stack || err.message);
        }

        updateing = false;
        return {success: false};
    });
}